<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<link rel="stylesheet" href="/plug-in/layui/css/layui.css" media="all">
<script src="/plug-in/layui/layui.js"></script>	
<script>
window.uploadFn = {
	readonly:false,
	uploadUrl: 	'/console/layui/upload/',
	uploadDeleteUrl:'/console/layui/upload/delete',
	uploadListUrl:'/console/layui/upload/list',
	deleteFn:function(fileId){
		if(fileId && fileId!=""){
			$.post(this.uploadDeleteUrl,{id: fileId},function(result){
				if(result.flag == true){
					layer.tips('删除成功!', '#demoList',{tips: [1, '#009688'], time: 3000});
				}else{
					layer.tips('删除失败!', '#demoList',{tips: [1, 'red'], time: 3000});
				}
			});
		}
	},
	listFn:function(fileIds,jq){
		var _this = this;
		var demoListView =  $("#demoList");
		$.post(this.uploadListUrl,{ids: fileIds},function(result){
			$.each(result || [], function (index, node) {
				node.name = node.original;
				var tr =  $(_this.createTr(index, node));
				demoListView.append(tr);
		        tr.find('.demo-delete').on('click', function(){
		          tr.remove();
		          var fileid = $(this).attr("fileid");
		          uploadFn.deleteFn(fileid);
		          uploadFn.setValue(jq);
		        });
            });
			/*只读模式*/
			if(window.uploadFn.readonly==true){
				$(".demo-delete").parent().html("只读");
			}
		});
	},
	setValue:function(jq){
		var fileId = [];
		$(".demo-delete").each(function(){
			var id = $(this).attr("fileid");
			if(id){ fileId.push(id);}
		});
		fileId = fileId.join(",");
		jq.textbox('setValue',fileId);
	},
	createTr:function(index,file){
		var fileid = file.id || "";
		var status = file.state || '待上传';
		if(status=='SUCCESS') status = '已上传';
		
		var tr = ['<tr id="upload-'+ index +'">'
          ,'<td>'+ file.name +'</td>'
          ,'<td>'+ (file.size/1014).toFixed(1) +'KB</td>'
          ,'<td>'+ status +'</td>'
          ,'<td>'
            ,'<button fileid="'+ fileid +'" class="layui-btn layui-btn-mini layui-btn-danger demo-delete">删除</button>'
          ,'</td>'
        ,'</tr>'].join('');
		return tr;
	}
};

$.parser.plugins.push("layuiupload");//注册扩展组件
$.fn.layuiupload = function (options, param) {//定义扩展组件
    //当options为字符串时，说明执行的是该插件的方法。
    if (typeof options == "string") { return $.fn.textbox.apply(this, arguments); }
    options = options || {};
    //当该组件在一个页面出现多次时，this是一个集合，故需要通过each遍历。
    return this.each(function () {
        var jq = $(this) , jqName = jq.attr("name") || jq.attr("id");
        //echo属性控制是否异步加载回显数据
        var myopts = $.extend({}, $.fn.textbox.parseOptions(this), options);
        $.fn.textbox.call(jq, myopts);
        
        var uploadP = myopts.upload || {};
        /*控件初始化及回显*/        
        setTimeout(function(){
        	window.uploadFn.readonly = uploadP.readonly || false;
			initUploadifybox();
        },100);
        
	    /*添加uploadify控件目标*/
        function initUploadifybox(){
	    	var aTools = '<a class="layui-btn layui-btn-small" id="layUpload"><i class="layui-icon">&#xe67c;</i>文件选择</a>&nbsp;&nbsp;&nbsp;'+
      	  	'<a class="layui-btn layui-btn-small" id="uploadAction"><i class="layui-icon">&#xe62f;</i>开始上传</a>';
	    	if(window.uploadFn.readonly==true) aTools = "";
        	var uploadifybox = '<div style="padding:5px;" class="layui-upload">'+
	          '<div style="width:200px;margin-bottom:15px;">'+ 
	          	aTools +
	      	  '</div>'+
        	  '<div class="layui-upload-list">'+
        	    '<table class="layui-table">'+
        	      '<thead>'+
        	        '<tr><th>文件名</th>'+
        	        '<th>大小</th>'+
        	        '<th>状态</th>'+
        	        '<th>操作</th>'+
        	      '</tr></thead>'+
        	      '<tbody id="demoList"></tbody>'+
        	    '</table>'+
        	  '</div>'+
        	'</div>';
	        var textbox =  jq.parent().find(".textbox");
	        textbox.find(".textbox-text").hide();
	        textbox.append(uploadifybox);
	        layui.use('upload', function(){
				  var upload = layui.upload;
				  var files = null;
				  //多文件列表示例
				  var demoListView = $('#demoList');
				  var uploadOpt = {
			    	elem: '#layUpload'
				    ,url: uploadFn.uploadUrl
				    ,accept: 'file'
				    ,multiple: true
				    ,auto: false
				    ,bindAction: '#uploadAction'
			    	,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
			    	    var upList = $("button[fileid='']");
			    		var upLen = upList.length;
			    		if(upLen>0){
				    	    layer.load(); //上传loading
			    		}else{
			    			layer.tips('请选择待上传文件!', '#demoList',{tips: [1, 'red'], time: 1000});
			    		}
			    	}
				    ,choose: function(obj){
				    	/*单文件上传数量控制*/
				    	var trLen = demoListView.find("tr").length;
				    	if(trLen>=1&& this.multiple==false){
				    		return false;
				    	}
					    files = obj.pushFile(); //将每次选择的文件追加到文件队列
					      //读取本地文件
					      obj.preview(function(index, file, result){
					    	var tr =  $(uploadFn.createTr(index,file));
					        //单个重传
					        tr.find('.demo-reload').on('click', function(){
					          obj.upload(index, file);
					        });
					        
					        //删除
					        tr.find('.demo-delete').on('click', function(){
					          delete files[index]; //删除对应的文件
					          tr.remove();
					          var fileid = $(this).attr("fileid");
					          uploadFn.deleteFn(fileid);
					          uploadFn.setValue(jq);
					        });
					        demoListView.append(tr);
					      });
				    }
				    ,done: function(res, index, upload){
				    	  layer.closeAll('loading');
					      if(res.flag == true){ //上传成功
					        var tr = demoListView.find('tr#upload-'+ index)
					        ,tds = tr.children();
					        tr.attr("fileid",res.data.id);//绑定id
					        tds.eq(2).html('<span style="color: #5FB878;">成功</span>');
					        //tds.eq(3).html(''); //清空操作
					        var btns = tds.eq(3);
					        btns.find(".demo-reload").remove();
					        btns.find(".demo-delete").attr("fileid",res.data.id);
						    delete files[index]; //删除文件队列已经上传成功的文件
						    uploadFn.setValue(jq);
					        return;
					      }
					      this.error(index, upload);
				    }
				    ,error: function(index, upload){
				    	 layer.closeAll('loading');
					      var tr = demoListView.find('tr#upload-'+ index)
					      ,tds = tr.children();
					      tds.eq(2).html('<span style="color: #FF5722;">失败</span>');
					      tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
				    }
				};
				uploadOpt = $.extend(true,uploadOpt, uploadP);
				var uploadListIns = upload.render(uploadOpt);
				uploadFn.listFn(jq.textbox('getValue'),jq);
			});
        }
    });
};
</script>